import requests
from bs4 import BeautifulSoup
from PIL import Image

urls = {
    'login': 'http://192.168.31.93/VZvipHtURf.php/index/login',
    'captcha': 'http://192.168.31.93/index.php?s=/captcha',
    'index': 'http://192.168.31.93/VZvipHtURf.php/index/index'
}

def get_session():
    s = requests.session()
    s.headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36',
    }
    return s

def get_captcha(s):
    '''获取验证码'''

    url = urls.get('captcha')
    r = s.get(url)
    captcha = 'captcha.png'
    with open(captcha, 'wb') as f:
        f.write(r.content)
    img = Image.open(captcha)
    img.show()
    captcha = input('验证码：')
    return captcha

def login():
    '''模拟登陆'''

    url = urls.get('login')
    s = get_session()

    r = s.get(url)
    with open('test.html', 'w') as f:
        f.write(r.text)
    soup = BeautifulSoup(r.text, 'lxml')
    token = soup.find('form', id='login-form').find('input').get('value')
    captcha = get_captcha(s)
    data = {
        '__token__': token,
        'username': 'admin',
        'password': 'admin123',
        'captcha': captcha,
    }

    # 登陆
    r = s.post(url,  data=data)
    print(r.text)
    url = urls.get('index')
    r = s.get(url)
    with open('index.html', 'w') as f:
        f.write(r.text)

login()